from flask import request
from wtforms import Form

from app.libs.error_code import ParameterException



class BaseForm(Form):
    def __init__(self):
        data = request.get_json(silent=True)   # 获取的是body里面的json参数, 使用request.get_json(silent=True) 替换request.json， 因为silent=True指定了静默模式，即时请求时候body里面没有json参数也不会报错，而request.json就会报错
        args = request.args.to_dict() # 获取的是query对应的参数
        super(BaseForm, self).__init__(data=data,**args)

    def validate_for_api(self):
        valid = super(BaseForm, self).validate()
        if not valid: # 如果参数没通过验证，抛出参数异常
            # form errors
            raise ParameterException(msg=self.errors)
        return self